package com.doodod.common.utils;

import java.util.Random;

/**
 * 用于随机数生成的工具类
 * User: 邱孝兵
 * Date: 2014/8/5
 * Time: 11:18
 */
public class RandomUtil {
    /**
     * 根据指定概率数组生成一个随机数
     *
     * @param pros
     * @return
     */
    public static int getRandomFromProArray(int[] pros) {
        int[] prefixSum = new int[pros.length];
        for (int i = 0; i < pros.length; i++) {
            if (pros[i] < 0)
                return -1;
            prefixSum[i] = pros[i];
            if (i > 0)
                prefixSum[i] += prefixSum[i - 1];
        }
        double random = Math.random();
        int num = (int) (prefixSum[prefixSum.length - 1] * random);
        for (int i = 0; i < prefixSum.length; i++) {
            if (num < prefixSum[i])
                return i;
        }
        return 0;
    }

    /**
     * 生成0，length之间的随机数
     *
     * @param length
     * @return
     */
    public static int getRandomFromLength(int length) {
        double random = Math.random();
        int num = (int) (random * length);
        return num;
    }

    /**
     * 在0，length之间生成N个不重复的随机数
     *
     * @param n
     * @param length
     * @return
     */
    public static int[] getNRandomFromLength(int n, int length) {
        if (n <= 0 || length <= 0 || n > length)
            return new int[0];
        Random random = new Random();
        boolean[] booleans = new boolean[length];
        int[] result = new int[n];
        for (int j = 0; j < n; j++) {
            /**得到n个不同的随机数 **/
            int randomInt = 0;
            do {
                randomInt = random.nextInt(length);
            } while (booleans[randomInt]);
            booleans[randomInt] = true;
            result[j] = randomInt;
        }

        return result;
    }


    public static void main(String[] args) {
//        int pros[] = {50, 30, 15, 3, 1};
//        int count[] = {0, 0, 0, 0, 0};
//        for (int i = 0; i < 10000; i++) {
//            count[getRandomFromProArray(pros)]++;
////            System.out.println(Math.random());
//        }
//        for (int i = 0; i < count.length; i++)
//            System.out.println(count[i]);
//        for (int i = 0; i < 50; i++)
//            System.out.println(getRandomFromLength(50));
    }
}
